package com.jah.picavue.client.view;

import java.util.ArrayList;
import com.google.gwt.event.logical.shared.ResizeEvent;
import com.google.gwt.event.logical.shared.ResizeHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.DockPanel;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.RootPanel;
import com.jah.picavue.client.Config;
import com.jah.picavue.client.model.Album;
import com.jah.picavue.client.model.User;

@SuppressWarnings("unchecked")
public class IndexView implements ResizeHandler {

	public final static IndexView INSTANCE = new IndexView();
	private User user = User.INSTANCE;

	private int cursor = 0;
	private ArrayList<Thumbnail> thumbs = new ArrayList();

	private RootPanel rootPanel= RootPanel.get(Config.ROOTPANELID);
	private DockPanel dock = new DockPanel();
	private Grid grid = new Grid();
	private int clientWidth;
	private int clientHeight;
	private String styleWidth;
	private String styleHeight;

	private IndexView() {}

	public void init() {
		// Generate Thumbnails
		for (int i = 0; i<user.getAlbumsCount(); i++) {
			Album a = user.getNextAlbum();
			thumbs.add(new Thumbnail(a.getID(), a.getThumb(), a.getName(), ""));
		}
		Window.addResizeHandler(this);
	}

	public void doView() {

		cursor = 0;
		calcSpace();
		styleWidth = (new Integer(clientWidth)).toString() + "px";
		styleHeight = (new Integer(clientHeight)).toString() + "px";

		rootPanel.clear();
		grid.clear();
		dock.clear();

		dock.setWidth(styleWidth);
		dock.setHeight(styleHeight);

		setGridSize(clientWidth, clientHeight - 60, thumbs.get(0).getWidth(),
				thumbs.get(0).getHeight(), (double) 20);

		// do the grid -
		final int rows = grid.getRowCount();
		final int cols = grid.getColumnCount();
		if (thumbs.size() < 1) return;
		grid.setCellSpacing(20);
		for (int row = 0; row < rows; row++) {
			for (int col = 0; col < cols; col++) {
				if (this.cursor == thumbs.size()) {
					row = rows;
					col = cols;
					continue;
				}
				grid.setWidget(row, col, thumbs.get(this.cursor));
				this.cursor++;  /* !! Note well that cursor increments past thumbs last index !! */
			}
		}

		dock.add(grid, DockPanel.CENTER);

		rootPanel.add(dock);
	}

	private void setGridSize(int gw, int gh, double tw, double th, double margin) {
		int rows = 0;
		int cols = (int) (gw / (tw+margin));
		int thumbs_count = thumbs.size();
		rows = ((thumbs_count % cols == 0) ? thumbs_count/cols : 1 + (int) thumbs_count/cols);
		if (rows < 1) rows = 1;
		if (cols < 1) cols = 1;
		grid.resize(rows,cols);
	}

	private void calcSpace() {
		int left = rootPanel.getAbsoluteLeft();
		int top = rootPanel.getAbsoluteTop();
		clientWidth = Window.getClientWidth() - (2* left);
		clientHeight = Window.getClientHeight() - (top + 50);
	}

	public void onResize(ResizeEvent event) {
		doView();
	}
	
	

}
